<template>
  <div class="edit">
    <div class="edit-title">
      <div class="title-left">
        <span class="title-1">考试管理</span> / <span class="title-2">{{ isEdit ? '编辑考试' : isDetail ? '考试详情' : '新增考试' }}</span>
      </div>
    </div>
    <div class="edit-content">
      <div class="edit-content-title">{{ isEdit ? '编辑考试' : isDetail ? '考试详情' : '新增考试' }}</div>
      <div class="edit-content-form">
        <el-form ref="examForm" :model="formData" label-width="115px" style="margin-bottom: 40px;" :rules="rules">
          <el-form-item label="考试名称" prop="fullName">
            <el-input v-model="formData.fullName" placeholder="请输入考试名称"></el-input>
          </el-form-item>
          <el-form-item label="试卷名称" prop="examPaperId">
            <el-select
              v-model="formData.paperName"
              placeholder="请选择试卷"
              @focus="openPaperDialog"
              style="width: 100%">
              <el-option
                :value="formData.paperName"
                :label="formData.paperName">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="考试类型" prop="categoryId">
            <el-radio v-model="formData.categoryId" label="1">理论考试</el-radio>
            <el-radio v-model="formData.categoryId" label="2">技能考试</el-radio>
            <el-radio v-model="formData.categoryId" label="3">自测</el-radio>
            <el-radio v-model="formData.categoryId" label="4">仅考试</el-radio>
          </el-form-item>

          <el-form-item label="试题顺序" prop="preventionQuestionRandomizes">
            <el-radio v-model="formData.preventionQuestionRandomizes" label="0">同序</el-radio>
            <el-radio v-model="formData.preventionQuestionRandomizes" label="1">随机</el-radio>
          </el-form-item>

          <el-form-item label="考试开放权限" prop="scopeRoles">
            <el-select v-model="formData.scopeRoles" placeholder="请选择考试开放权限" style="width: 100%">
              <el-option v-for="(item, index) in examScopeOptions" :id="item.id" :key="index"
              :label="item.fullName" :value="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="考试编号" prop="description">
            <el-input v-model="formData.description" placeholder="请输入考试编号"></el-input>
          </el-form-item>
          <el-form-item label="考试有效期" prop="validTime">
            <el-date-picker
              v-model="formData.validTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="考试通过分数" prop="passScore">
            <el-input v-model="formData.passScore" placeholder="请输入考试通过分数设置"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="edit-footer" v-show="!isDetail || (isDetail && showCancelButton)">
      <el-button @click="handleCancel" class="footer-btn" v-if="!isDetail || (isDetail && showCancelButton)">取消</el-button>
      <el-button type="primary" :loading="isAdding" :disabled="isAdding" @click="handleSubmit" class="footer-btn" v-if="!isDetail">保存</el-button>
    </div>

    <!-- 试卷选择弹窗 -->
    <el-dialog title="选择试卷" :visible.sync="paperDialogVisible" width="70%">
      <div class="dialog-content">
        <!-- 搜索栏 -->
        <div class="search-bar">
          <el-form :inline="true" :model="paperSearchForm">
            <el-form-item label="试卷名称">
              <el-input v-model="paperSearchForm.name" placeholder="请输入试卷名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchPapers">查询</el-button>
              <el-button @click="resetPaperSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 试卷列表 -->
        <el-table
          :data="paperList"
          border
          style="width: 100%"
          highlight-current-row
          @current-change="handlePaperCurrentRowChange"
          ref="paperTable">
          <el-table-column width="55">
            <template slot-scope="scope">
              <el-radio v-model="selectedPaper" :label="scope.row">&nbsp;</el-radio>
            </template>
          </el-table-column>
          <el-table-column prop="fullName" label="试卷名称"></el-table-column>
          <el-table-column prop="paperType" label="试卷类型">
            <template slot-scope="scope">
              {{ scope.row.paperType === '1' ? '普通试卷' : '随机试卷' }}
            </template>
          </el-table-column>
          <el-table-column prop="creatorTime" label="创建时间"></el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="set-table-pg-right">
          <el-pagination
            @size-change="handlePaperSizeChange"
            @current-change="handlePaperCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="paperDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelectPaper">确 定</el-button>
      </span>
    </el-dialog>
    <!--选择题目-->
    <el-drawer :visible.sync="openAddTitle" :with-header="false" :direction="direction" size="60%">
      <div class="drawer-title">
        <div class="drawer-title-left">{{ addTitle }}</div>
        <div class="drawer-title-right" @click="openAddTitle = false">
          <i class="el-icon-close" style="font-size: 14px; color: #a4afca"></i>
        </div>
      </div>
      <div class="drawer-content" style="display: flex; flex-direction: column; gap: 24px">
        <div class="search-form">
          <el-form :inline="true" :model="drawerSearchForm" class="demo-form-inline">
            <!-- 只在手动出题模式下显示题型选择 -->
            <el-form-item label="题型" v-if="formData.paperType === '1'">
              <el-select v-model="drawerSearchForm.questionType" placeholder="请选择题型" clearable>
                <el-option label="判断题" value="1"></el-option>
                <el-option label="填空题" value="2"></el-option>
                <el-option label="选择题" value="3"></el-option>
                <el-option label="问答题" value="4"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题目标签">
              <!-- <el-input v-model="drawerSearchForm.labels" placeholder="请输入题干关键字"></el-input> -->
              <el-select
                v-model="drawerSearchForm.labels"
                placeholder="请选择题目标签"
                :style="{ width: '100%' }"
              >
                <el-option
                  v-for="(item, index) in labelsOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.enCode"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="难度">
              <el-select v-model="drawerSearchForm.difficulty" placeholder="请选择难度" clearable>
                <el-option label="简单" value="1"></el-option>
                <el-option label="中等" value="2"></el-option>
                <el-option label="困难" value="3"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题干">
              <el-input v-model="drawerSearchForm.title" placeholder="请输入题干关键字"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">查询</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>

          <!-- 自动出题模式下显示题目数量选择 -->
          <div v-if="formData.paperType === '2'" class="question-count-form">
            <el-form :inline="true" :model="autoQuestionCounts">
              <el-form-item label="判断题数量">
                <el-input-number 
                  v-model="autoQuestionCounts.determine" 
                  :min="0" 
                  :max="questionTypeLimits.determine"
                  size="small">
                </el-input-number>
                <span class="question-count-limit">/{{ questionTypeLimits.determine }}</span>
              </el-form-item>
              <el-form-item label="填空题数量">
                <el-input-number 
                  v-model="autoQuestionCounts.blank" 
                  :min="0" 
                  :max="questionTypeLimits.blank"
                  size="small">
                </el-input-number>
                <span class="question-count-limit">/{{ questionTypeLimits.blank }}</span>
              </el-form-item>
              <el-form-item label="选择题数量">
                <el-input-number 
                  v-model="autoQuestionCounts.multiple" 
                  :min="0" 
                  :max="questionTypeLimits.multiple"
                  size="small">
                </el-input-number>
                <span class="question-count-limit">/{{ questionTypeLimits.multiple }}</span>
              </el-form-item>
              <el-form-item label="问答题数量">
                <el-input-number 
                  v-model="autoQuestionCounts.answers" 
                  :min="0" 
                  :max="questionTypeLimits.answers"
                  size="small">
                </el-input-number>
                <span class="question-count-limit">/{{ questionTypeLimits.answers }}</span>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <el-table ref="multipleTable1" :data="tableData2" tooltip-effect="dark" style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column label="题目标签">
            <template slot-scope="scope">
              {{ scope.row.labels | dynamicText(labelListOptions) }}
              <!-- <div class="gizall">
                <div class="tag" v-if="scope.row.labels">{{ scope.row.labels }}</div>
                <span v-else>--</span>
              </div> -->
            </template>
          </el-table-column>
          <el-table-column prop="questionType" label="题目类型">
            <template slot-scope="scope">
              <div class="gizall">
                <div class="tag" v-if="scope.row.questionType">{{ getQuestionTypeName(scope.row.questionType) }}</div>
                <span v-else>--</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="题干关键字">
            <template slot-scope="scope">
              <div class="gizall">
                <div class="gjz" v-if="scope.row.title">{{ scope.row.title }}</div>
                <span v-else>--</span>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <div class="set-r">
          <div>
            <div class="pagination-container">
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage2" :page-sizes="[10, 20, 50, 100]" :page-size="pageSize2"
                layout="sizes, prev, pager, next, total" :total="total2">
              </el-pagination>
            </div>
          </div>
          <div><el-button @click="addExam()">确定</el-button></div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import request from '@/utils/request'
import { getQuestionList } from "@/api/test/question";
import { addExam, getList, UpdateExam } from './api/exam'

export default {
  name: 'ExamAdd',
  data() {
    return {
      isAdding: false,
      disableAll: false,
      formData: {
        fullName: '',  // 考试名称
        examPaperId: '', // 试卷ID
        description: '', // 考试编号
        startDatetime: null, // 开始时间
        endDatetime: null, // 结束时间
        startDatetimeTemp: [], // 时间范围
        examLength: 30, // 考试时长
        passLine: 60, // 及格分数
        certificateId: '', // 证书ID
        paperType: "1",
        // preventionQuestionRandomizes: null, // 题目随机
        preventionItemRandomizes: null, // 选项随机
        preventionToggleScreen: 0, // 切屏限制
        preventionToggleScreenSecond: 0, // 切屏次数
        preventionFace: null, // 人脸识别
        preventionIp: null, // IP限制
        preventionAddr: null, // 地址限制
        examRepeat: null, // 重复考试
        categoryId: '1', // 考试类型，默认为理论考试
        preventionQuestionRandomizes: '0',  
        examRepeatNum: '', // 重复考试次数
        examAnswers: 'submitAfter', // 答案显示
        examOpen: null, // 开放考试
        examSign: null, // 考试签名
        examPass: null, // 考试通过
        examCompletionGrading: null, // 完成评分
        examEssayGrading: null, // 主观题评分
        learningPeriod: 0, // 学习周期
        learningCredit: 0, // 学习学分
        learningIntegral: 0, // 学习积分
        scopeType: 'all', // 范围类型
        scope: '[]', // 范围
        examinerUserIds: '["admin"]', // 考官用户IDs
        creatorUserId: '', // 创建用户ID
        creatorTime: '', // 创建时间
        enabledMark: '1', // 启用标记
        id: '', // ID
        scopeOrganizes: '', // 组织范围
        // scopeRoles: [],
        scopeRoles: '',
        validTime: [],  // 临时存储时间范围
        paperName: '',  // 试卷名称
        totalScore: '', // 试卷总分
        passScore: 60,  // 考试通过分数设置
        examRepeatType: 'before',
      },
      tableData2: [{}],
      direction: "rtl",
      openAddTitle: false,
      addTitle: '手动选题',
      activeName: "first",
      tableData3: [],
      tableData4: [],
      selectedManual: [],
      selectedAuto: [],
      currentPage2: 1,
      pageSize2: 10,
      total2: 0,
      paperDialogVisible: false,
      paperSearchForm: {
        name: ''
      },
      paperList: [],
      selectedPaper: null,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      scoreData: [ {
        singleScore: 0,
        multipleScore: 0,
        judgeScore: 0,
        fillScore: 0,
        questionScore: 0,
        passScore: 60
      } ],
      drawerSearchForm: {
        questionType: '',
        labels: '',
        difficulty: '',
        title: ''
      },
      autoQuestionCounts: {
        determine: 0,  // 判断题数量
        blank: 0,      // 填空题数量
        multiple: 0,   // 选择题数量
        answers: 0     // 问答题数量
      },
      questionTypeLimits: {
        determine: 0,
        blank: 0,
        multiple: 0,
        answers: 0
      },
      rules: {
        fullName: [
          { required: true, message: '请输入考试名称', trigger: 'blur' }
        ],
        examPaperId: [
          { required: true, message: '请选择试卷', trigger: 'change' }
        ],
        scopeRoles: [
          { required: true, message: '请选择考试开放权限', trigger: 'change' }
        ],
        description: [
          { required: true, message: '请输入考试编号', trigger: 'blur' }
        ],
        // validTime: [
        //   { required: true, message: '请选择考试有效期', trigger: 'change' }
        // ]
      },
      isEdit: false,
      isDetail: false,
      showCancelButton: true,
      originalFormData: null, // 存储原始表单数据
      originalScoreData: null, // 存储原始分数数据
      examScopeOptions: [
        {
          "id": "668834371960045637",
          "fullName": "培训考试用户",
          "enCode": "0004",
          "type": "全局",
          "organizeInfo": null,
          "description": "",
          "enabledMark": 1,
          "creatorTime": 1741598943000,
          "sortCode": 0,
          "roleType": "业务角色"
        },
        {
            "id": "669460031602688197",
            "fullName": "大众用户",
            "enCode": "04",
            "type": "全局",
            "organizeInfo": null,
            "description": "",
            "enabledMark": 1,
            "creatorTime": 1741748112000,
            "sortCode": 0,
            "roleType": "业务角色"
        }
      ],
      isShowQueBtn: true,
      labelsOptions: [],
      labelListOptions:[],
    }
  },
  watch: {
    'formData.paperType': {
      handler(newVal) {
        if (newVal === '1') {
          this.activeName = 'first';
          this.addTitle = '手动选题';
          this.tableData4 = [];
          this.selectedAuto = [];
        } else if (newVal === '2') {
          this.activeName = 'second';
          this.addTitle = '自动选题';
          this.tableData3 = [];
          this.selectedManual = [];
        } else if (newVal === '3') {
          this.activeName = 'three';
          this.addTitle = '分值设置';
        }
      },
      immediate: true
    },
    activeName: {
      handler(newVal) {
        let paperType;
        if (newVal == 'first') {
          paperType = '1';
          this.addTitle = '手动选题';
          this.isShowQueBtn = true;
        }
        else if (newVal == 'second') {
          paperType = '2';
          this.addTitle = '自动选题';
          this.isShowQueBtn = true;
        }
        else if (newVal == 'three') {
          paperType = '3';
          this.addTitle = '分值设置';
          this.isShowQueBtn = false;
        }
        this.formData.paperType = paperType;

        // const paperType = newVal === 'first' ? '1' : '2';
        // if (this.formData.paperType !== paperType) {
        //   this.formData.paperType = paperType;
        //   this.addTitle = newVal === 'first' ? '手动选题' : '自动选题';
        // }
      },
      immediate: true
    }
  },
  created() {
    // 获取路由参数
    const { type, id, formData, scoreData } = this.$route.query;
    
    this.isEdit = type === 'edit';
    this.isDetail = type === 'detail';

    // 如果是编辑或详情模式，且有数据，则填充表单
    if ((this.isEdit || this.isDetail) && formData) {
      try {
        
        const parsedFormData = JSON.parse(formData);
        // 处理时间格式
        if (parsedFormData.validTime && Array.isArray(parsedFormData.validTime)) {
          this.formData.validTime = parsedFormData.validTime;
        }
        // 处理 scopeRoles
        // parsedFormData.scopeRoles = parsedFormData.scopeRoles ? parsedFormData.scopeRoles.split(',') : [];
        parsedFormData.scopeRoles = parsedFormData.scopeRoles ? parsedFormData.scopeRoles : [];
        this.formData = { ...this.formData, ...parsedFormData };

        // 保存原始数据的深拷贝
        if (this.isEdit) {
          this.originalFormData = JSON.parse(JSON.stringify(this.formData));
        }
      } catch (error) {
        console.error('解析表单数据失败:', error);
      }
    }

    // 填充分数数据
    if ((this.isEdit || this.isDetail) && scoreData) {
      try {
        const parsedScoreData = JSON.parse(scoreData);
        this.scoreData = [parsedScoreData];
        // 保存原始分数数据的深拷贝
        if (this.isEdit) {
          this.originalScoreData = JSON.parse(JSON.stringify(this.scoreData[0]));
        }
      } catch (error) {
        console.error('解析分数数据失败:', error);
      }
    }

    // 如果是详情模式，禁用所有输入
    if (this.isDetail) {
      this.$nextTick(() => {
        // 禁用表单输入
        const form = this.$refs.examForm;
        if (form) {
          const formItems = form.$el.querySelectorAll('.el-form-item');
          formItems.forEach(item => {
            const inputs = item.querySelectorAll('input, textarea, select');
            inputs.forEach(input => {
              input.setAttribute('disabled', 'disabled');
            });
            const radioButtons = item.querySelectorAll('.el-radio');
            radioButtons.forEach(radio => {
              radio.setAttribute('disabled', 'disabled');
            });
          });
        }

        // 禁用表格中的输入
        const tableInputs = document.querySelectorAll('.el-input-number__decrease, .el-input-number__increase, .el-input-number__input');
        tableInputs.forEach(input => {
          input.setAttribute('disabled', 'disabled');
        });
      });
    }

    // 获取开放权限
    // this.getExamScopeList();

  },
  methods: {
      // 获取 标签 选项
      getLabelsOptions() {
      this.$store
        .dispatch("base/getDictionaryData", {
          encode: "questionLabels",
        })
        .then((res) => {
          this.labelsOptions = res;
          // 转换
          let arr = [];
          for(let i in res) {
            let obj = {};
            obj.fullName = res[i].fullName;
            obj.id = res[i].enCode;
            arr.push(obj);
          }
          this.labelListOptions = arr;
        });
    },
    // 获取开放权限
    getExamScopeList() {
      request({
        url: `api/permission/Role?n=1743175635&organizeId=0&keyword=&currentPage=1&pageSize=20&sort=desc&sidx=&typeList=ApplicationRole&menuId=07029F61-993A-4A46-BF56-20DE382F4F66`,
        method: 'get'
      })
      .then(res => {
        this.examScopeOptions = res.data.list
      })
    },
    handleCancel() {
      this.$router.go(-1)
    },
    // 比较两个值是否相等
    isValueEqual(value1, value2) {
      if (Array.isArray(value1) && Array.isArray(value2)) {
        return JSON.stringify(value1) === JSON.stringify(value2);
      }
      return value1 === value2;
    },

    // 获取修改过的字段
    getChangedFields() {
      const changedFields = {};
      
      // 检查formData中的变化
      if (this.originalFormData) {
        Object.keys(this.formData).forEach(key => {
          if (!this.isValueEqual(this.formData[key], this.originalFormData[key])) {
            changedFields[key] = this.formData[key];
          }
        });
      }

      // 检查scoreData中的变化
      if (this.originalScoreData) {
        Object.keys(this.scoreData[0]).forEach(key => {
          if (!this.isValueEqual(this.scoreData[0][key], this.originalScoreData[key])) {
            changedFields[key] = this.scoreData[0][key];
          }
        });
      }

      return changedFields;
    },
    handleClick(tab) {
      this.activeName = tab.name;

      // this.$forceUpdate();
      // console.log(tab.name,'===tab==333')
      // this.$nextTick(() => {
      //   const newQuestionType = tab.name === 'first' ? '1' : '2';
      //   // 避免循环更新
      //   if (this.drawerSearchForm.questionType !== newQuestionType) {
      //     this.drawerSearchForm.questionType = newQuestionType;
      //   }
      //   if (tab.name === 'first') {
      //     this.$refs.multipleTable1.doLayout();
      //   } else {
      //     this.$refs.multipleTable2.doLayout();
      //   }
      // });
    },
    
    // 添加新的辅助方法用于转换题目类型
    getQuestionType(type) {
      switch (Number(type)) {
        case 1:
          return 'determine'; // 判断题
        case 2:
          return 'blank'; // 填空题
        case 3:
          return 'multiple'; // 选择题
        case 4:
          return 'answers'; // 问答题
        default:
          return '';
      }
    },
    addExamList() {
      if (this.activeName === 'first') {
        this.addTitle = '手动选题';
        this.openAddTitle = true;
        this.formData.paperType = '1';
        this.drawerSearchForm = {
          questionType: '',
          labels: '',
          difficulty: '',
          title: ''
        };
      } else if (this.activeName === 'second') {
        this.addTitle = '自动选题';
        this.openAddTitle = true;
        this.formData.paperType = '2';
        this.drawerSearchForm = {
          questionType: '',
          labels: '',
          difficulty: '',
          title: ''
        };
      }
      // 打开抽屉后再获取题目列表
      this.$nextTick(() => {
        this.currentPage2 = 1; // 重置页码
        this.getexamList();
        this.getLabelsOptions();
      });
    },
    async getexamList() {
      try {
        let params = {
          currentPage: this.currentPage2,
          pageSize: this.pageSize2,
          labels: this.drawerSearchForm.labels,
          difficulty: this.drawerSearchForm.difficulty,
          title: this.drawerSearchForm.title
        };
        
        // 只在手动出题模式下添加 questionType 参数
        if (this.formData.paperType === '1') {
          params.questionType = this.drawerSearchForm.questionType;
        }
        
        // 移除空值参数
        Object.keys(params).forEach(key => {
          if (!params[key]) {
            delete params[key];
          }
        });

        const response = await getQuestionList(params);
        if (response && response.data) {
          this.tableData2 = response.data.list.map(item => ({
            id: item.id || '',
            questionType: this.getQuestionTypeNumber(item.questionType),
            title: item.title || '--',
            labels: item.labels || ''
          }));

          this.total2 = parseInt(response.data.pagination.total);
          this.currentPage2 = parseInt(response.data.pagination.currentPage);
          this.pageSize2 = parseInt(response.data.pagination.pageSize);
          
          // 更新题型数量限制
          this.updateQuestionTypeLimits();
        }
      } catch (error) {
        console.error("Error fetching list:", error);
        this.$message.error("获取列表失败");
      }
    },
    searchQuestion() {
      let params = {
        title: this.input
      };
      const response = getQuestionList(params);
      if (response && response.data) {
        this.tableData2 = response.data.list.map(item => ({
          ...item,
        }));
        this.total2 = parseInt(response.data.pagination.total);
        this.currentPage2 = parseInt(response.data.pagination.currentPage);
        this.pageSize2 = parseInt(response.data.pagination.pageSize);
      }
    },
    handleManualSelectionChange(val) {
      this.selectedManual = val;
    },
    handleAutoSelectionChange(val) {
      this.selectedAuto = val;
    },
    getQuestionTypeNumber(type) {
      switch (type) {
        case 'determine':
          return 1;
        case 'blank':
          return 2;
        case 'multiple':
          return 3;
        case 'answers':
          return 4;
        default:
          return type ? Number(type) : 0;
      }
    },
    getQuestionTypeName(type) {
      const numType = typeof type === 'string' ? this.getQuestionTypeNumber(type) : Number(type);
      switch (numType) {
        case 1:
          return '判断题';
        case 2:
          return '填空题';
        case 3:
          return '选择题';
        case 4:
          return '问答题';
        default:
          return '--';
      }
    },
    handleSelectionChange(val) {
      this.selectedQuestions = val;
    },
    handleSizeChange(val) {
      this.pageSize2 = val;
      this.getexamList();
    },
    handleCurrentChange(val) {
      this.currentPage2 = val;
      this.getexamList();
    },
    handleSearch() {
      this.currentPage2 = 1;
      this.getexamList();
    },
    resetSearch() {
      this.drawerSearchForm = {
        questionType: '',
        labels: '',
        difficulty: '',
        title: ''
      };
      if (this.formData.paperType === '2') {
        Object.keys(this.autoQuestionCounts).forEach(key => {
          this.autoQuestionCounts[key] = 0;
        });
      }
      this.handleSearch();
    },
    addExam() {
      if (this.formData.paperType === '2') {
        // 自动出题模式
        const totalCount = Object.values(this.autoQuestionCounts).reduce((a, b) => a + b, 0);
        if (totalCount === 0) {
          this.$message.warning('请选择要添加的题目数量');
          return;
        }

        // 按题型分组现有题目
        const questionsByType = {};
        this.tableData2.forEach(question => {
          const type = this.getQuestionType(question.questionType);
          if (!questionsByType[type]) {
            questionsByType[type] = [];
          }
          questionsByType[type].push(question);
        });

        // 随机选择每种类型的题目
        const selectedQuestions = [];
        for (const [type, count] of Object.entries(this.autoQuestionCounts)) {
          if (count > 0) {
            const availableQuestions = questionsByType[type] || [];
            if (availableQuestions.length < count) {
              this.$message.warning(`${this.getQuestionTypeName(this.getQuestionTypeNumber(type))}数量不足`);
              return;
            }
            
            // 随机选择指定数量的题目
            const shuffled = [...availableQuestions].sort(() => 0.5 - Math.random());
            selectedQuestions.push(...shuffled.slice(0, count));
          }
        }

        // 添加到表格
        const newQuestions = selectedQuestions.filter(newQuestion => {
          return !this.tableData4.some(existingQuestion => existingQuestion.id === newQuestion.id);
        });
        
        this.tableData4 = [...this.tableData4, ...newQuestions];
        this.$message.success('添加题目成功');
        this.openAddTitle = false;
        
        // 重置计数器
        Object.keys(this.autoQuestionCounts).forEach(key => {
          this.autoQuestionCounts[key] = 0;
        });
      } else {
        // 手动出题模式的原有逻辑
        if (!this.selectedQuestions || this.selectedQuestions.length === 0) {
          this.$message.warning('请选择要添加的试题');
          return;
        }

        const mappedQuestions = this.selectedQuestions.map(question => ({
          id: question.id,
          title: question.title,
          questionType: question.questionType,
          labels: this.getQuestionTypeName(question.questionType)
        }));

        const newQuestions = mappedQuestions.filter(newQuestion => {
          return !this.tableData3.some(existingQuestion => existingQuestion.id === newQuestion.id);
        });
        this.tableData3 = [...this.tableData3, ...newQuestions];
        this.$message.success('添加题目成功');
        this.openAddTitle = false;
        this.selectedQuestions = [];
      }
      // 计算总分
      // this.compareTotalScore();
    },
    editRow(row) {
      if (this.activeName === 'first') {
        const index = this.tableData3.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.tableData3.splice(index, 1);
        }
      } else if (this.activeName === 'second') {
        const index = this.tableData4.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.tableData4.splice(index, 1);
        }
      }
      this.$message.success('删除成功');
      // 计算总分
      // this.compareTotalScore();
    },
    // 更新题型数量限制
    updateQuestionTypeLimits() {
      const counts = {
        determine: 0,
        blank: 0,
        multiple: 0,
        answers: 0
      };
      
      this.tableData2.forEach(item => {
        const type = this.getQuestionType(item.questionType);
        if (counts[type] !== undefined) {
          counts[type]++;
        }
      });
      
      this.questionTypeLimits = counts;
    },

    // // 计算试卷总分
    // compareTotalScore() {
    //   // 总分默认为0
    //   let totalScore = 0;
    //   const questions = this.formData.paperType == "1" ? this.tableData3 : this.tableData4;
    //   if (questions.length > 0) {
    //     questions.forEach(item => {
    //       if (item.questionType == "1") {
    //         // 判断题
    //         totalScore += this.scoreData[0].judgeScore || 0;
    //       } else if (item.questionType == "2") {
    //         // 填空题
    //         totalScore += this.scoreData[0].fillScore || 0;
    //       } else if (item.questionType == "3") {
    //         // 选择题
    //         totalScore += this.scoreData[0].multipleScore || 0;
    //       } else if (item.questionType == "4") {
    //         // 问答题
    //         totalScore += this.scoreData[0].questionScore || 0;
    //       }
    //     })
    //   }
    //   // 总分赋值
    //   this.formData.totalScore = totalScore;
    // },

    // 确定提交
    handleSubmit() {

      // 防止重复点击
      if (this.isAdding) return;
      this.isAdding = true;

      this.$refs.examForm.validate(async (valid) => {
        if (valid) {

          // const scores = this.scoreData[0];
          // const totalScore = Number(scores.singleScore || 0) +
          //   Number(scores.multipleScore || 0) +
          //   Number(scores.judgeScore || 0) +
          //   Number(scores.fillScore || 0) +
          //   Number(scores.questionScore || 0);

          // if (totalScore !== 100) {
          //   this.$message.error('总分必须等于100分');
          //   return;
          // }

          try {

            // 处理时间
            const startTime = this.formData.validTime ? new Date(this.formData.validTime[0]).getTime() : null;
            const endTime = this.formData.validTime ? new Date(this.formData.validTime[1]).getTime() : null;

            const scope = [
              {
                'type': 'company',
                'selectArr': []
              },
              { 'type': 'department', 'selectArr': [] },
              {
                'type': 'Role',
                'selectArr': [this.formData.scopeRoles]
              },
              { 'type': 'Position', 'selectArr': [] },
              { 'type': 'Group', 'selectArr': [] },
              { 'type': 'user', 'selectArr': [] },
              { 'type': 'exclude', 'selectArr': [] }
            ]
            let params;
            if (this.isEdit) {
              // 编辑模式：完全匹配后端字段
              params = {
                folders: "[\"638100473177446981\"]",
                'scopeType': 'select',
                'scope': JSON.stringify(scope),
                // 'scopeRoles': this.formData.scopeRoles.join(','),
                'scopeRoles': this.formData.scopeRoles,
                'scopeOrganizes': '',
                'scopeGroups': '',
                'scopePositions': '',
                'scopeUsers': '',
                'scopeExcludeUsers': '',
                id: this.formData.id,
                parentId: null,
                fullName: this.formData.fullName,
                examPaperId: this.formData.examPaperId,
                paperName: this.formData.paperName,
                description: this.formData.description || "",
                startDatetime: startTime,
                endDatetime: endTime,
                examLength: this.formData.examLength || 30,
                // passLine: this.scoreData[0].passScore || 60,
                passLine: this.formData.passScore || 60,
                certificateId: this.formData.certificateId || "",
                preventionItemRandomizes: this.formData.preventionItemRandomizes || 0,
                preventionToggleScreen: this.formData.preventionToggleScreen || 0,
                preventionToggleScreenSecond: this.formData.preventionToggleScreenSecond || 0,
                preventionFace: this.formData.preventionFace || null,
                preventionIp: this.formData.preventionIp || null,
                preventionAddr: this.formData.preventionAddr || null,
                examRepeat: this.formData.examRepeat || 0,
                categoryId: this.formData.categoryId || "",
                examRepeatType: this.formData.examRepeatType || "",
                preventionQuestionRandomizes: this.formData.preventionQuestionRandomizes || '0',
                examRepeatNum: this.formData.examRepeatNum || null,
                examAnswers: this.formData.examAnswers || "passAfter",
                examOpen: this.formData.examOpen || 0,
                examSign: this.formData.examSign || null,
                examPass: this.formData.examPass || 0,
                examCompletionGrading: this.formData.examCompletionGrading || 0,
                examEssayGrading: this.formData.examEssayGrading || null,
                learningPeriod: this.formData.learningPeriod || 0,
                learningCredit: this.formData.learningCredit || 0,
                learningIntegral: this.formData.learningIntegral || 0,
                examinerUserIds: this.formData.examinerUserIds || "[\"admin\"]",
                // enabledMark: this.formData.enabledMark || "1",
                enabledMark: "1",
                startDatetimeTemp: [startTime, endTime]
              };

            } else {
              // this.formData.scopeRoles = this.formData.scopeRoles.join(',');
              // 新增模式：包含所有字段
              params = {
                ...this.formData,
                startDatetime: startTime,
                endDatetime: endTime,
                startDatetimeTemp: [startTime, endTime],
                passLine: this.formData.passScore || 60,
                // ...this.scoreData[0],
                // passLine: this.scoreData[0].passScore
              };
              params.folders = "[\"638100473177446981\"]";
              params.scopeType = 'select';
              params.scope = JSON.stringify(scope);
              // params.scopeRoles = this.formData.scopeRoles.join(',');
              params.scopeRoles = this.formData.scopeRoles;
            }

            // 删除不需要的字段
            delete params.validTime;
            delete params.paperName;

            let res;
            if (this.isEdit) {
              res = await UpdateExam(params);
            } else {
              res = await addExam(params);
            }

            if (res.code === 200) {
              this.$message.success(this.isEdit ? '修改成功' : '添加成功');
              this.$router.push('/test/examManagement');
            } else {
              this.$message.error(res.msg || (this.isEdit ? '修改失败' : '添加失败'));
            }
          } catch (error) {
            this.isAdding = false;
            console.error(this.isEdit ? '修改失败:' : '添加失败:', error);
            this.$message.error(this.isEdit ? '修改失败' : '添加失败');
          }
        }
      });
    },
    openPaperDialog() {
      this.paperDialogVisible = true;
      if (!this.paperList.length) {
        this.getTableList();
      }
    },

    async getTableList() {
      try {
        const params = {
          currentPage: this.currentPage,
          pageSize: this.pageSize,
          fullName: this.paperSearchForm.name
        };
        const res = await getList(params);
        if (res.code === 200) {
          this.paperList = res.data.list || [];
          const pagination = res.data.pagination || {};
          this.currentPage = pagination.currentPage || 1;
          this.pageSize = pagination.pageSize || 10;
          this.total = pagination.total || 0;
          
          if (this.formData.examPaperId) {
            const selectedPaper = this.paperList.find(item => item.id === this.formData.examPaperId);
            if (selectedPaper) {
              this.selectedPaper = selectedPaper;
            }
          }
        } else {
          this.$message.error(res.msg || '获取试卷列表失败');
        }
      } catch (error) {
        console.error('获取试卷列表失败:', error);
        this.$message.error('获取试卷列表失败');
      }
    },

    searchPapers() {
      this.currentPage = 1;
      this.getTableList();
    },

    resetPaperSearch() {
      this.paperSearchForm.name = '';
      this.searchPapers();
    },

    handlePaperCurrentRowChange(row) {
      this.selectedPaper = row;
    },

    confirmSelectPaper() {
      if (!this.selectedPaper) {
        this.$message.warning('请选择试卷');
        return;
      }
      this.formData.examPaperId = this.selectedPaper.id;
      this.formData.paperName = this.selectedPaper.fullName;
      this.paperDialogVisible = false;
    },

    handlePaperSizeChange(val) {
      this.pageSize = val;
      this.getTableList();
    },

    handlePaperCurrentChange(val) {
      this.currentPage = val;
      this.getTableList();
    }
  }
}
</script>

<style lang="scss" scoped>
.edit {
  height: 100%;
  box-sizing: border-box;

  .edit-title {
    font-weight: 500;
    font-size: 19px;
    color: #536387;
    line-height: 29px;
    text-align: left;

    .title-left {
      display: flex;
      align-items: center;

      .back-icon {
        font-size: 20px;
        margin-right: 10px;
        cursor: pointer;
        color: #536387;
        
        &:hover {
          color: #2265ee;
        }
      }
    }

    .title-1 {
      color: #536387;
      padding-right: 11px;
    }

    .title-2 {
      padding-left: 11px;
      color: #323232;
    }
  }

  .edit-content {
    background: #fff;
    margin-top: 32px;
    padding: 32px 32px 100px;
    border-radius: 4px;

    .edit-content-title {
      font-size: 21px;
      line-height: 21px;
      position: relative;
      padding-left: 11px;
      margin-bottom: 32px;
      border-bottom: 1px solid #e2e7f5;
      padding-bottom: 16px;

      &:before {
        content: "";
        position: absolute;
        width: 4px;
        height: 21px;
        top: 0;
        left: 0;
        background: #2265ee;
      }
    }

    .edit-content-form {
      padding: 0 24px;
    }
  }

  .edit-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 80px;
    background: #fff;
    padding: 0 32px;
    display: flex;
    align-items: center;
    justify-content: flex-end;
    box-shadow: 0 -2px 4px rgba(0,0,0,0.05);

    .footer-btn {
      width: 100px;
      height: 40px;
      margin-left: 16px;
    }
  }

  .sjform-tip {
    width: 100%;
    height: 46px;
    background: #fffbe8;
    border-radius: 4px;
    line-height: 46px;
    color: #ed6a0c;
    box-sizing: border-box;
    padding-left: 16px;
    margin-bottom: 16px;
    font-size: 14px;
    i {
      margin-right: 8px;
    }
  }
}

.set-btn-add {
    position: absolute;
    right: 40px;
    z-index: 1000;
}
.set-r {
  display: flex;
  width: 100%;

  div:nth-child(1) {
    flex: 8;
  }

  div:nth-child(2) {
    flex: 2;

    .el-button {
      width: 106px;
      height: 36px;
      background-color: #2265ee;
      border: 1px solid #2265ee;
      color: #fff;

      &:active {
        opacity: 0.8;
      }
    }
  }
}

.form-input {
  width: 300px !important;
}

.form-textarea {
  width: 100% !important;
}

.grid-content {
  margin-bottom: 20px;
}

.dialog-content {
  .search-bar {
    margin-bottom: 20px;
  }
  
  .set-table-pg-right {
    margin-top: 20px;
    text-align: right;
  }
}
</style>